import { history } from 'umi';
import { message } from 'antd';
import api from 'api';
import { pathToRegexp } from 'path-to-regexp';

const { loginUser } = api

export default {
  namespace: 'login',
  state: { errorMsg: { message: null, timeStamp: 0 } },
  subscriptions: {
    setupHistory({ dispatch, history }) {  // eslint-disable-line
      return history.listen(({ pathname, state }) => {
        if (pathToRegexp("/login").exec(pathname)) {
        }
      })
    },
  },
  effects: {
    *loginStudent({ payload, callback }, { put, call, select }) {

      const data = yield call(loginUser, payload);
      console.log("登陆返回结果:", data);

      if (data.code === 0) {
        yield put({ type: "errorHandle", payload: data.msg })
      }
      else {
        yield put({
          type: "user/updateUser",
          payload: {
            userInfo: {
              // userName: data.data.TrueName,
              userId: data.data.Id,
              userType: 1,
              account: data.data.UserName, password: data.data.UserPwd,
            },
          }
        });

        history.push("/homePage");
        message.success("登录成功！");
      }
    },
  },
  reducers: {
    errorHandle(_, { payload: message }) {
      return { errorMsg: { message, timeStamp: Date.now() } }
    }
  }
};